import time

from scapy.sendrecv import sniff

from DataBase_online_MYSQL import insert_MYSQL_DB
from utilsA import *
from DataBase_redis import *



iface_name= 'Realtek PCIe GbE Family Controller'
file_Name="C:\\data.pcap"

filter_mac='DA0203040506'
catch_count=0
skip_count=1000

hex_start=28#十六进制下data的开始位
hex_end=36#十六进制下data的结束位
hex_data_count=1#数据量

count=0
x=0

queue2 = None


def handelPacket(p):  # p捕获到的数据包
    mac_addr = hexdump2(p, 13, 24)      #12到24是mac地址段
    # print(mac_addr)
    if mac_addr==filter_mac:  #如果是FPGA发送的数据帧才解析存入数据库
        p_str = hexdump2(p, hex_start, hex_end)
        p_str = '0x' + p_str

        # 数据库写入
        global count  # count为帧编号
        count += 1
        if count % skip_count == 0:
            t = time.time()  # 获取时间戳

            global x  # x为在数据库中的编号
            x += 1
            y = hex_to_float(p_str)  # y为IEEE754经过转码
            append_to_log(time.strftime("%Y-%m-%d %H_%M_%S", time.localtime()) + ':第' + str(count) + '帧上的IEEE754浮点数：' + p_str + '>>>>>>十进制浮点数：' + str(y) + '\n')  # GUI文本区输出信息
            # insertDB(t, x, y)  # 插入数据库
            insert_one_data_to_redisDB(t, x, y)
            # 可以修改为批量插入：
            # tlist.append(str(t))
            # xlist.append(str(x))
            # ylist.append(str(y))
            # data = [(tlist[i], xlist[i], ylist[i]) for i in range(0, len(xlist))]
            # utils.insertDB_data(data)

            # 后期可以继续优化：多线程插入
            # t = threading.Thread(target=utils.insertDB, args=(t,x,y))
            # t.start()
            # t.join()

def snifferIface(adaperName,fileName,filterRules,catchCount,skipCount,hexStart,hexEnd,dataCount):
    #如有需要可以保存为pcap文件
    # pcap = sniff(prn=handelPacket, offline="idp.pcap")
    global skip_count, hex_start, hex_end, hex_data_num
    skip_count, hex_start, hex_end, hex_data_num=skipCount,hexStart,hexEnd,dataCount
    global filter_mac
    filter_mac=filterRules.upper()
    #过滤规则需要安装windump，所以此处禁用
    filterRules=None

    sniff(count=catchCount,
          prn=handelPacket,
          filter=filterRules,
          # filter=None,
          timeout=None,
          offline=fileName,
          stop_filter=None,
          iface=adaperName)

if __name__ == "__main__":
    pass
    sniff(count=0,
          store=0,
          offline=file_Name,
          prn=handelPacket,
          filter=None,
          L2socket=None,
          timeout=None,
          opened_socket=None,
          stop_filter=None)

